<?php

namespace app\health\controller;

use app\health\model\HealthCart;
use app\health\validate\CartValidate;

class Cart extends ApiBase
{
    /**
     * 我的购物车列表
     * @Author 张旭鹏
     * @DateTime 2023-06-14
     */
    public function lists()
    {
        $where['a.user_id'] = array('eq', $this->auth->id);
        $data               = HealthCart::alias('a')
            ->where($where)
            ->join('health_goods x', 'a.goods_id = x.id', 'left')
            ->join('health_goods_attr o', 'a.goods_attr_id = o.id', 'left')
            ->field('a.id,a.number,x.goods_name,x.image,x.price,x.mix_title,x.lineation_price,o.attr_name,o.price as attr_price,o.image as attr_image')
            ->order('a.id desc')
            ->select();
        foreach ($data as $item) {
            $item->image      = cdnurl($item->image, true);
            $item->attr_image = cdnurl($item->attr_image, true);
        }
        $this->success('获取成功', $data);
    }

    /**
     * 加入购物车
     * @Author 张旭鹏
     * @DateTime 2023-06-14
     */
    public function add()
    {
        $params                 = (new CartValidate())->goCheck('add');
        $user_id                = $this->auth->id;
        $where['user_id']       = array('eq', $this->auth->id);
        $where['goods_id']      = array('eq', $params['goods_id']);
        $where['goods_attr_id'] = array('eq', $params['goods_attr_id']);
        //判断这个商品属性是否存在
        $isFind = HealthCart::where($where)->find();
        if ($isFind) {
            //则数量添加
            $result = $isFind->setInc('number', $params['number']);
        } else {
            //则添加
            $data['user_id']       = $user_id;
            $data['goods_id']      = $params['goods_id'];
            $data['goods_attr_id'] = $params['goods_attr_id'];
            $data['number']        = $params['number'];
            $data['state']         = 1;
            $result                = HealthCart::create($data);
        }
        if ($result) {
            $this->success('加入购物车成功');
        }
        $this->error('加入购物车失败');
    }

    /**
     * 编辑购物车
     * @Author 张旭鹏
     * @DateTime 2023-06-14
     */
    public function edit()
    {
        $params = (new CartValidate())->goCheck('edit');
        HealthCart::where('id', $params['id'])->setField('number', $params['number']);
        $this->success('编辑成功');
    }

    /**
     * 删除购物车
     * @Author 张旭鹏
     * @DateTime 2023-06-14
     */
    public function delete()
    {
        $params = $this->request->post();
        $result = HealthCart::where('id', 'in', $params['ids'])->delete();
        if ($result) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }
}
